<template>
  <div class="category-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h1>帖子分类管理</h1>
      <a-button type="primary" @click="handleAdd">
        <template #icon><PlusOutlined /></template>
        新增分类
      </a-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.categoryName"
            placeholder="搜索分类名称"
            allow-clear
            @input="handleSearch"
          >
            <template #prefix><SearchOutlined /></template>
          </a-input>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="searchForm.isEnabled"
            placeholder="状态筛选"
            allow-clear
            style="width: 100%"
            @change="handleSearch"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-button @click="handleReset">重置</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 分类列表表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="categoryList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <!-- 分类名称列 -->
          <template v-if="column.key === 'categoryName'">
            <span class="category-name">{{ record.categoryName }}</span>
          </template>

          <!-- 排序值列 -->
          <template v-else-if="column.key === 'categorySort'">
            <span>{{ record.categorySort }}</span>
          </template>

          <!-- 状态列 -->
          <template v-else-if="column.key === 'isEnabled'">
            <a-switch
              :checked="record.isEnabled === 1"
              :loading="statusChanging[record.id]"
              @change="(checked) => toggleStatus(record, checked)"
            />
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)"> 编辑 </a-button>
              <a-popconfirm
                title="确定要删除这个分类吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" size="small" danger> 删除 </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑分类Modal -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEditing ? '编辑分类' : '新增分类'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirm-loading="submitting"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
        <a-form-item label="分类名称" name="categoryName">
          <a-input
            v-model:value="formData.categoryName"
            placeholder="请输入分类名称"
            :maxlength="50"
          />
        </a-form-item>

        <a-form-item label="排序值" name="categorySort">
          <a-input-number
            v-model:value="formData.categorySort"
            placeholder="请输入排序值（数字越小越靠前）"
            :min="1"
            :max="999"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="状态" name="isEnabled">
          <a-radio-group v-model:value="formData.isEnabled">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { debounce } from 'lodash-es'
import { postCategoryService } from '@/api/postCategory'
import type { PostCategory, PostCategoryPageParams, PostCategoryRequest, PageResult } from '@/types'

// 响应式数据
const loading = ref(false)
const categoryList = ref<PostCategory[]>([])
const modalVisible = ref(false)
const isEditing = ref(false)
const submitting = ref(false)
const formRef = ref()

// 状态切换loading状态
const statusChanging = reactive<Record<number, boolean>>({})

// 搜索表单
const searchForm = reactive<Partial<PostCategoryPageParams>>({
  categoryName: '',
  isEnabled: undefined,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表单数据
const formData = reactive<PostCategoryRequest>({
  categoryName: '',
  categorySort: 1,
  isEnabled: 1,
})

// 表单验证规则
const formRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' },
  ],
  categorySort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '排序值必须在1-999之间', trigger: 'blur' },
  ],
  isEnabled: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 表格列配置
const columns = [
  {
    title: '分类名称',
    key: 'categoryName',
    dataIndex: 'categoryName',
  },
  {
    title: '排序值',
    key: 'categorySort',
    dataIndex: 'categorySort',
    width: 120,
    align: 'center' as const,
  },
  {
    title: '状态',
    key: 'isEnabled',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    width: 120,
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center' as const,
  },
]

// 加载分类列表
const loadCategoryList = async () => {
  loading.value = true
  try {
    const params: PostCategoryPageParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    }

    const result = await postCategoryService.getPostCategoryPage(params)

    categoryList.value = result.result || []
    pagination.total = result.total || 0
  } catch (error) {
    message.error('加载分类列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 防抖搜索
const handleSearch = debounce(() => {
  pagination.current = 1
  loadCategoryList()
}, 500)

// 重置搜索
const handleReset = () => {
  searchForm.categoryName = ''
  searchForm.isEnabled = undefined
  pagination.current = 1
  loadCategoryList()
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadCategoryList()
}

// 简化的状态切换处理
const toggleStatus = async (record: PostCategory, checked: boolean) => {
  statusChanging[record.id] = true
  try {
    await postCategoryService.updatePostCategory({
      ...record,
      isEnabled: checked ? 1 : 0,
    })

    // 更新本地数据
    const index = categoryList.value.findIndex((item) => item.id === record.id)
    if (index !== -1) {
      categoryList.value[index].isEnabled = checked ? 1 : 0
    }

    message.success(`${checked ? '启用' : '禁用'}成功`)
  } catch (error) {
    message.error(`${checked ? '启用' : '禁用'}失败`)
    console.error('状态更新失败:', error)
  } finally {
    statusChanging[record.id] = false
  }
}

// 新增分类
const handleAdd = () => {
  isEditing.value = false
  modalVisible.value = true
  resetFormData()
}

// 编辑分类
const handleEdit = (record: PostCategory) => {
  isEditing.value = true
  modalVisible.value = true
  formData.id = record.id
  formData.categoryName = record.categoryName
  formData.categorySort = record.categorySort
  formData.isEnabled = record.isEnabled
}

// 删除分类
const handleDelete = async (id: number) => {
  try {
    await postCategoryService.deletePostCategory(id)
    message.success('删除成功')
    loadCategoryList()
  } catch (error) {
    message.error('删除失败')
    console.error('删除失败:', error)
  }
}

// Modal确认
const handleModalOk = () => {
  formRef.value?.validate().then(async () => {
    submitting.value = true
    try {
      if (isEditing.value) {
        await postCategoryService.updatePostCategory(formData)
        message.success('更新成功')
      } else {
        await postCategoryService.createPostCategory(formData)
        message.success('创建成功')
      }

      modalVisible.value = false
      loadCategoryList()
    } catch (error) {
      message.error(isEditing.value ? '更新失败' : '创建失败')
      console.error('操作失败:', error)
    } finally {
      submitting.value = false
    }
  })
}

// Modal取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 重置表单数据
const resetFormData = () => {
  formData.id = undefined
  formData.categoryName = ''
  formData.categorySort = 1
  formData.isEnabled = 1
  formRef.value?.resetFields()
}

// 组件挂载时加载数据
onMounted(() => {
  loadCategoryList()
})
</script>

<style scoped lang="scss">
.category-management {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 500;
    }
  }

  .search-section {
    margin-bottom: 24px;
    padding: 20px;
    background: #fafafa;
    border-radius: 8px;
  }

  .table-section {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
  }

  .category-name {
    font-weight: 500;
  }

  :deep(.ant-modal) {
    .ant-form-item {
      margin-bottom: 20px;
    }
  }
}
</style>